<?php
// +----------------------------------------------------------------------
// | 店铺充值记录表
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use base\pay\WxApi;
use base\other\Strings;
use app\common\model\Shop;
use app\common\model\ShopBill;
use app\common\model\UserRechargeRule;

class ShopRecharge extends Model
{
	use \base\model\ModelTrait;
	
	// 自动完成
	protected $insert = ['no','type'];
	protected function setNoAttr() {
		return  'dcz'.(Strings::createOrderNo());
    }
    protected function setTypeAttr() {
		return 'wx';
    }
	/**
    * 验证规则
    */
	protected $rule = [
		'shop_id|店铺id'=>'require|integer',
		'price|充值金额'=>'require|float|min:0.1',
	];
	
	
	/**
	* 获取最新的一条充值状态
	*/
	public function getRechargeStatus($shop_id){
		$order = self::where('shop_id',$shop_id)->limit(1)->order("add_time desc")->find();
		$payInfo =  (new WxApi)->orderQuery($order->no,true);
		if($order->status == 0 && $payInfo['trade_state_desc']=="支付成功"){
			$order->status = 1;
			$order->status_time = date("Y-m-d H:i:s");
			$order->transaction_id = $payInfo['transaction_id'];
			$order->save();
			return event('VipRechargeSuccess',$order);
		}
		return $order->status;
	}
	
	/**
	* 充值成功
	*/
	public function paySuccess($no,$transaction_id){
		$order = self::where('no',$no)->find();
		if($order->status == 1) return true;
		
		//添加到账户
    	$shopId = $order['shop_id'];
    	$price = floatval($order['price']);
    	
    	$shop = Shop::get($shopId);
    	
    	//入账
    	$shop->balance = ['inc', $price];
    	$shop->save();
    	
    	//添加流水账
    	$mark = '会员充值入账'.$price.'元';
    	ShopBill::income("充值",$shopId,'balance','recharge',$price,$order['no'],0,$mark);
    	
    	//更改订单状态
    	$order->status = 1;
		$order->status_time = date("Y-m-d H:i:s");
		$order->transaction_id = $transaction_id;
		return $order->save();
	}
	
		
}
